package org.jash.shop2202.shop

import android.graphics.Paint
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.google.android.material.snackbar.BaseTransientBottomBar.BaseCallback
import com.google.android.material.snackbar.Snackbar
import org.jash.shop2202.R
import org.jash.shop2202.BR
import org.jash.shop2202.databinding.FragmentCartBinding
import org.jash.shop2202.entity.Cart
import org.jash.shop2202.entity.CartItem
import org.jash.shop2202.mvvm.BaseFragment
import org.jash.shop2202.utils.CommonAdapter
import org.jash.shop2202.utils.Event
import org.jash.shop2202.utils.bus

@Route(path = "/shop/cart")
class CartFragment : BaseFragment<FragmentCartBinding, CartViewModel>() {
    private val cart by lazy { Cart() }
    private val adapter by lazy { CommonAdapter<CartItem>({R.layout.item_cart to BR.item}, cart.data) }
    override fun initData() {
        viewModel.cartItemLiveData.observe(viewLifecycleOwner) {
            bus.postValue("购物车数量" to it.size)
            adapter += it
        }
        viewModel.deleteLiveData.observe(viewLifecycleOwner) {
            bus.postValue("购物车数量" to cart.data.size)
        }
        viewModel.loadCartItem()
    }

    override fun initView() {
        binding.cart = cart
        binding.recycler.adapter = adapter
        binding.price.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG or binding.price.paint.flags
//        binding.allChecked.addOnCheckedStateChangedListener { _, state ->
//            cart.allChecked = state
//        }
        binding.buy.setOnClickListener {
            ARouter.getInstance()
                .build("/shop/pay")
                .withString("content", cart.data.filter(CartItem::checked).joinToString("\n") { "${it.goods_desc} x ${it.count}"})
                .withFloat("price", cart.coupon)
                .navigation()
        }
    }

    @Event("更新购物车")
    fun updateCart(s:String) {
        cart.notifyPropertyChanged(BR.allChecked)
    }

    @Event("删除购物车")
    fun deleteCart(item:CartItem) {
        val position = adapter.removeIf { it.id == item.id }
        Snackbar.make(binding.container, "删除了${item.goods_desc}", Snackbar.LENGTH_LONG)
            .setAction("撤销"){}
            .addCallback(object :BaseCallback<Snackbar>() {
                override fun onDismissed(transientBottomBar: Snackbar?, event: Int) {
                    if (event == Snackbar.Callback.DISMISS_EVENT_ACTION) {
                        adapter.add(position, item)
                    } else {
                        viewModel.deleteCart(item.id)
                    }
                }
            })
            .show()
    }

}